package com.amos.think.user.command.query;

import com.amos.think.domain.gateway.UserGateway;
import com.amos.think.domain.user.UserEntity;
import com.amos.think.dto.UserRegisterCmd;
import com.amos.think.dto.data.UserVO;
//import com.amos.think.user.command.mq.ProduceService;
import com.amos.think.service.mq.MessageService;
import com.amos.think.user.assembler.UserAssembler;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
public class UserMongoQueryExe {


    @Autowired
    private UserGateway userGateway;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired
//    private ProduceService produceService;
    @Autowired
    private MessageService messageService;

    public void execute(UserRegisterCmd userRegisterCmd) throws Exception {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(userRegisterCmd.getName()));
        long count = mongoTemplate.count(query, UserEntity.class);
        if (count > 0){
            throw new RuntimeException("该用户已经存在!");
        }
        messageService.sendJsonMessage("topic", UserAssembler.toEntity(userRegisterCmd));
//        UserEntity userEntity = userGateway.saveMongo(userRegisterCmd);
        //将用户数据存入到redis中
        redisTemplate.opsForValue().set(userRegisterCmd.getName(),userRegisterCmd);
//
    }

    public List<UserVO> executeAllUser(){
//        produceService.sendMessage("test-topic","准备删除数据了");
        return userGateway.getAllUser();
    }

    public void executeUpdate(UserRegisterCmd userRegisterCmd) {
        Query query = new Query(Criteria.where("name").is(userRegisterCmd.getName()));
        Update update = new Update().set("username", userRegisterCmd.getUsername())
                .set("name", userRegisterCmd.getName())
                .set("gender", userRegisterCmd.getGender())
                .set("description", userRegisterCmd.getDescription());
        userGateway.updateUserInfo(query,update,UserEntity.class);
    }

    public void executeDelete(String userId) {
        Query query = new Query(Criteria.where("_id").is(userId));
        userGateway.delete(query,UserEntity.class);
    }
}
